package com.sx.pipeline.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.text.format.DateFormat
import android.util.Log
import androidx.core.content.FileProvider
import java.io.File
import java.text.SimpleDateFormat


/**
 * author : zhouyouqiang
 * e-mail : 1638473898@qq.com
 * date   : 2022/3/9 16:39
 * desc   :
 * version: 1.0
 */
object AndroidUtil {
    fun getVersionName(context: Context): String {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            "" + packageInfo.versionName
        } catch (e: Exception) {
            "Unknown"
        }
    }

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private const val MIN_CLICK_DELAY_TIME = 500
    private var lastClickTime: Long = 0

    fun isFastClick(): Boolean {
        var flag = false
        val curClickTime = System.currentTimeMillis()
        if (curClickTime - lastClickTime >= MIN_CLICK_DELAY_TIME) {
            flag = true
        }
        lastClickTime = curClickTime
        return flag
    }


    /**
     *
     * 方法描述 隐藏银行卡号中间的字符串（使用*号），显示前四后四
     *
     */
    fun hideCardNo(cardNo: String): String? {
        if (cardNo.length!=19) {
            return cardNo
        }
        val length = cardNo.length
        val beforeLength = 4
        val afterLength = 4
        //替换字符串，当前使用“*”
        val replaceSymbol = "*"
        val sb = StringBuffer()
        for (i in 0 until length) {
            if (i < beforeLength || i >= length - afterLength) {
                sb.append(cardNo[i])
            } else {
                sb.append(replaceSymbol)
            }
        }
        return sb.toString()
    }


    /**
     * 获取当前app version code
     */
    fun getAppVersionCode(context: Context): Int {
        var appVersionCode: Long = 0
        try {
            val packageInfo = context.applicationContext
                .packageManager
                .getPackageInfo(context.packageName, 0)
            appVersionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                packageInfo.longVersionCode
            } else {
                packageInfo.versionCode.toLong()
            }
        } catch (e: PackageManager.NameNotFoundException) {
            e.message?.let { Log.e("", it) }
        }
        return appVersionCode.toInt()
    }

     fun phoneHide(phone: String): String {
        val sb = StringBuilder()
        if (!TextUtils.isEmpty(phone) && phone.length > 6) {
            for (i in phone.indices) {
                val c = phone[i]
                if (i in 3..6) {
                    sb.append('*')
                } else {
                    sb.append(c)
                }
            }
        }
        return sb.toString()
    }



    /**
     * 创建自定义输出目录
     *
     * @return
     */
    private fun getSandboxPath(mContext:Context): String? {
        val externalFilesDir: File? =mContext.getExternalFilesDir("")
        val customFile = File(externalFilesDir?.absolutePath, "Sandbox")
        if (!customFile.exists()) {
            customFile.mkdirs()
        }
        return customFile.absolutePath + File.separator
    }

    fun date2TimeStamp(date: String?, format: String?): String? {
        try {
            val sdf = SimpleDateFormat(format)
            return java.lang.String.valueOf(sdf.parse(date).getTime() / 1000)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return ""
    }

    /**
     * @param time
     * @return yy-MM-dd HH:mm格式时间
     */
    fun conversionTime(time: Long, format: String = "yyyy-MM-dd HH:mm:ss"): String {
        return DateFormat.format(format, time).toString()
    }

    fun listToString(list: List<String?>?): String? {
        if (list == null) {
            return null
        }
        val result = StringBuilder()
        var first = true

        //第一个前面不拼接","
        for (string in list) {
            if (first) {
                first = false
            } else {
                result.append(",")
            }
            result.append(string)
        }
        return result.toString()
    }

    fun toCallPhone(phone: String,context: Context){
        val  intent=Intent(Intent.ACTION_DIAL)
        val data= Uri.parse("tel:$phone")
        intent.data = data
        context.startActivity(intent)
    }

    //安装apk
    fun tryInstallApk(activity: Activity, file: File) {
        if (!file.exists()) {
            return
        }
        val intent = Intent(Intent.ACTION_VIEW)
        //Android7.0之后需要使用FileProvider创建Uri
        val apkUri: Uri = getUri(activity, file)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //Android8.0开始需要获取应用内安装权限
                val allowInstall = activity.packageManager.canRequestPackageInstalls()
                //如果还没有授权安装应用，去设置内开启应用内安装权限
                if (!allowInstall) {
                    //注意这个是8.0新API
                    val packageUri = Uri.parse("package:" + activity.packageName)
                    val intentX = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri)
                    activity.startActivityForResult(intentX, 0x001)
                    return
                }
            }
            //Android N开始必须临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        activity.startActivity(intent)
    }

    //获取文件Uri
    fun getUri(context: Context, file: File?): Uri {
        val uri: Uri
        uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //第二个参数为 包名.fileprovider
            FileProvider.getUriForFile(context, context.packageName + ".fileprovider", file!!)
        } else {
            Uri.fromFile(file)
        }
        return uri
    }
}